import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { changeFlag } from "../reducers/flagReducer";
import {
  asyncQueryList,
  asyncDelList,
  asyncAddList,
} from "../reducers/listReducer";

export default function User() {
  const [info, setinfo] = useState({
    username: "",
    userage: "",
  });

  let dispatch = useDispatch();
  let list = useSelector((state) => state.listInfo);

  useEffect(() => {
    dispatch(changeFlag(false));
    //页面加载请求数据
    if (!list.length) {
      dispatch(asyncQueryList({})); //查询所有
    }

    return () => {
      dispatch(changeFlag(true));
    };
  }, []);

  return (
    <div>
      <div>
        <div>
          用户名{" "}
          <input
            value={info.username}
            onChange={(e) => {
              setinfo({
                ...info,
                username: e.target.value,
              });
            }}
          />{" "}
        </div>
        <div>
          年龄{" "}
          <input
            value={info.userage}
            onChange={(e) => {
              setinfo({
                ...info,
                userage: e.target.value,
              });
            }}
          />{" "}
        </div>
        {/* <button
          onClick={() => {
            dispatch(asyncAddList({...info,cb:(res)=>{
                console.log(res);
            }}));
            //如果用户名重复了怎么办
          }}
        >
          新增
        </button> */}
        <button
          onClick={async () => {
            let res = await dispatch(asyncAddList(info));
            //如果用户名重复了怎么办
            console.log(res);
          }}
        >
          新增
        </button>
      </div>
      <div className="tr">
        <div className="td">编号</div>
        <div className="td">用户名</div>
        <div className="td">年龄</div>
        <div className="td">操作</div>
      </div>
      {list.map((item) => {
        return (
          <div className="tr" key={item.id}>
            <div className="td">{item.id}</div>
            <div className="td">{item.username}</div>
            <div className="td">{item.userage}</div>
            <div
              className="td"
              onClick={() => {
                dispatch(asyncDelList(item.id));
              }}
            >
              删除
            </div>
          </div>
        );
      })}
    </div>
  );
}
